//
//  CCKeyChain.m
//  CCKit
//
//  Created by tucici on 2019/3/29.
//  Copyright © 2019 tucici. All rights reserved.
//

#import "CCKeyChain.h"

@implementation CCKeyChain

+ (NSMutableDictionary*)getKeychainQuery:(NSString*)key
{
    return[NSMutableDictionary dictionaryWithObjectsAndKeys:
           (id)kSecClassGenericPassword,(id)kSecClass,
           key,(id)kSecAttrService,
           key,(id)kSecAttrAccount,
           (id)kSecAttrAccessibleAfterFirstUnlock,(id)kSecAttrAccessible, nil];
}

+ (void)save:(NSString *)key value:(nonnull id)value
{
    //Get search dictionary
    NSMutableDictionary *keychainQuery = [self getKeychainQuery:key];
    //Delete old item before add new item
    SecItemDelete((CFDictionaryRef) keychainQuery);
    //Add new object to searchdictionary(Attention:the data format)
    [keychainQuery setObject:[NSKeyedArchiver archivedDataWithRootObject:value]forKey:(id)kSecValueData];
    //Add item to keychain with the searchdictionary
    SecItemAdd((CFDictionaryRef)keychainQuery,NULL);
}
+ (id)load:(NSString *)key
{
    id ret =nil;
    //Get search dictionary
    NSMutableDictionary*keychainQuery = [self getKeychainQuery:key];
    //Configure the search setting
    //Since in our simple case we areexpecting only a single attribute to be returned (the password) wecan set the attribute kSecReturnData to kCFBooleanTrue
    [keychainQuery setObject:(id)kCFBooleanTrue forKey:(id)kSecReturnData];
    [keychainQuery setObject:(id)kSecMatchLimitOne forKey:(id)kSecMatchLimit];
    CFDataRef keyData =NULL;
    if(SecItemCopyMatching((CFDictionaryRef)keychainQuery,(CFTypeRef*)&keyData) ==noErr){
        @try{
            ret =[NSKeyedUnarchiver unarchiveObjectWithData:(__bridge NSData*)keyData];
        }@catch(NSException *e) {
            NSLog(@"Unarchiveof %@ failed: %@",key, e);
        }@finally{
        }
    }
    if(keyData)
        CFRelease(keyData);
    return ret;
    
}
+ (void)rm:(NSString *)key
{
    NSMutableDictionary*keychainQuery = [self getKeychainQuery:key];
    SecItemDelete((CFDictionaryRef)keychainQuery);
}
@end
